const express     = require('express');
const app         = express();

// 引入body-parser用于解析post参数
var bodyParser = require('body-parser');

// 需要use的 application/json
app.use(bodyParser.json()); 
// application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended: true
})); 

const constants     = require('./data/constants');
const sipServer     = require('./sip/server');
const dbManager     = require('./db/dbmanager');
const settingModel  = require('./model/setting');
const log4js        = require('./data/log');
const logger        = log4js.getLogger('request');
const mediaCtrl     = require('./controller/v1/media');
const scheduleCtrl  = require('./pipe/schedule');
const zlmediakitCtrl= require('./pipe/zlmediakit');

// 设置express日志
log4js.useLogger(app,logger);

// express 引入静态资源
const static = express.static('public');
app.use(static);

// express 引入28181操作路由
const gb28181Router = require('./routers/gb28181');
app.use(gb28181Router);

// express 引入媒体服务器操作路由
const mediaRouter = require('./routers/media');
app.use(mediaRouter);

// express 引入设备操作路由
const channelRouter = require('./routers/channel');
app.use(channelRouter)
const deviceRouter = require('./routers/device');
app.use(deviceRouter)

// express 引入管理员路由
const adminRouter = require('./routers/admin');
app.use(adminRouter);

// express 引入参数设置模块
const settingRouter = require('./routers/setting');
app.use(settingRouter);

//TODO:加载权限管理 https://github.com/OptimalBits/node_acl

/**
 * 启动 http 服务
 */ 
let server = app.listen(constants.http.port, function () {
  let host = server.address().address;
  let port = server.address().port;
  logger.info("启动 Web 服务: http://%s:%s", host, port);
  
  /**从数据库加载配置 */
  dbManager.open();

  // 恢复上次关闭前的设置
  constants.load(async ()=>{
    
    let sipSetting = await settingModel.load();
    if(sipSetting.sip_rtp_host){
      /**
       * 常量里有些地址替换
       */
      constants.initUrl(sipSetting.sip_rtp_host);
      logger.info('启动ZLMediaKit服务');
     // await zlmediakitCtrl.start();
      logger.info('释放 rtp 资源');
      mediaCtrl.resetRtpServer();
      logger.info('启动计划任务检查日志文件');
      scheduleCtrl.start();
      logger.info('启动GB28181的sip服务');
      sipServer.start(sipSetting);
    }else{
      logger.error('没有设置sip_rtp_host变量');
    }
  });
  
  process.on('SIGINT', () => {
      logger.info('停止服务，保存临时文件，停止计划任务');
      scheduleCtrl.stop();
      constants.save(async ()=>{
        dbManager.close();
        logger.info('退出ZLMediaKit媒体服务');
     //   await zlmediakitCtrl.stop();
        process.exit(0);
      });
  });

  // 捕获异常
  process.on('unhandledRejection', (reason, p) => {
    logger.error('Unhandled Rejection at:', p, 'reason:', reason);
  });
});